package fishBids.group3.behaviour.bank;

import fishBids.group3.AgBank;
import fishBids.group3.behaviour.bank.model.Account;
import fishBids.group3.common.Constants;
import fishBids.group3.communicationobjects.ToCreateAccount;
import fishBids.group3.utils.Utils;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.util.leap.HashMap;
import jade.util.leap.Map;

public class BankCreateAccountBehaviour extends CyclicBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4218560108006303061L;
	
	public BankCreateAccountBehaviour(Codec codec, Ontology ontology, AgBank bankAg){
		this.codec = codec;
		this.ontology = ontology;
		this.bankAg = bankAg;
	}

	@Override
	public void action() {

		// Waits for sellProduct requests
		// Receive the message 
		//System.out.println("Bank>>> Esperando una solicitud de creacion de cuenta"); 
		ACLMessage msg = bankAg.receive(MessageTemplate.and(
				MessageTemplate.MatchPerformative(ACLMessage.REQUEST),
				MessageTemplate.MatchProtocol(Constants.CREATE_ACCOUNT) )); 
		if(msg != null ){
		
			try {
				ToCreateAccount toCreateAccount = (ToCreateAccount) msg.getContentObject();
				AID aid = toCreateAccount.getAgentID();
				if( this.bankAg.getAgentsAccounts().containsKey(aid.getName()) ){
//					System.out.println("\n\n\n\n\n\n***** An account for agent " + aid.getName() + " was created before.");
					Utils.sendMessage(ACLMessage.FAILURE, codec, ontology, aid, Constants.CREATE_ACCOUNT, bankAg);
					return;
				}
				
				Account account = new Account();
				account.setOwnerID(aid);
				double initialBalance = Double.parseDouble(Utils.getProperty(Constants.INITIAL_MONEY));
//				System.out.println("Bank >>> initial bank account money: " + initialBalance);
				account.setBalance(initialBalance);
				this.bankAg.getAgentsAccounts().put(aid.getName(), account);
				this.createItemsObtained(aid);
				Utils.sendMessage(ACLMessage.INFORM, codec, ontology, msg.getSender(), Constants.CREATE_ACCOUNT, bankAg);
				//System.out.println("bank>> recibio solicitud de creacion de cuenta, no voy a hacer nada!!! ");				
			} catch (UnreadableException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}else{
			block();
		}

	}
	
	private void createItemsObtained(AID aid) {
		
		Map itemsObtained = new HashMap();
		itemsObtained.put(Constants.CALAMARI_TYPE.getType(), new Double(0) );
		itemsObtained.put(Constants.PRAWN_TYPE.getType(), new Double(0) );
		itemsObtained.put(Constants.TUNA_TYPE.getType(), new Double(0) );
		itemsObtained.put(Constants.SALMON_TYPE.getType(), new Double(0) );
		
		this.bankAg.getAgentsItemsObtained().put(aid.getName(),itemsObtained);
	}

	Codec codec;
	Ontology ontology;
	AgBank bankAg;

}
